<?php


namespace app\api\logic;


use app\api\model\Code as CodeModel;
use app\api\model\User as UserModel;
use app\api\model\Merchant as MerchantModel;
use app\api\model\Area as AreaModel;
use app\api\model\Airport as AirportModel;
use app\api\model\Category as CategoryModel;
use app\api\model\Label as LabelModel;
use app\api\model\QrCode as QrCodeModel;
use think\facade\Session;
use think\Db;
class Tool
{
    private static $userID;
    private static $userType;

    public function __construct()
    {
        self::$userID=Session::get('userId');
        self::$userType=Session::get('userType');
    }

    /**
     * 换绑手机号
     * @param $data
     * @return mixed
     */
    public function phone($data){
        $type=self::$userType;
        $res=Common::checkCode($data,config('data.code_type.phone'),$type);
        if($res['req']==0){
            return $res;
        }

        if($type==config('data.role_type.user')){
            $count=UserModel::where(['phone'=>$data['phone'],'status'=>1])->count();
            if($count){
                $result['req']=0;
                $result['msg']='The current phone number is already bound and cannot be changed';
                return $result;
            }
            UserModel::update(['phone'=>$data['phone'],'phone_code'=>$data['phone_code']],['id'=>self::$userID]);
        }else{
            $count=MerchantModel::where(['account'=>$data['phone']])->where('status','neq',-1)->count();
            if($count){
                $result['req']=0;
                $result['msg']='The current phone number is already bound and cannot be changed';
                return $result;
            }
            MerchantModel::update(['account'=>$data['phone'],'phone_code'=>$data['phone_code']],['id'=>self::$userID]);
        }

        $result['req']=1;
        return $result;
    }

    /**
     * 换绑邮箱
     * @param $data
     * @param $type 1:商户2；用户
     * @return mixed
     */
    public function email($data){
        $type=self::$userType;

        $res=Common::checkCode($data,config('data.code_type.email'),$type);
        if($res['req']==0){
            return $res;
        }

        if($type==config('data.role_type.user')){
            $count=UserModel::where(['email'=>$data['email'],'status'=>1])->count();
            if($count){
                $result['req']=0;
                $result['msg']='The current email is already bound and cannot be changed';
                return $result;
            }
            UserModel::update(['email'=>$data['email']],['id'=>self::$userID]);
        }else{
            //商户更新
            $count=MerchantModel::where(['account'=>$data['email']])->where('status','neq',-1)->count();
            if($count){
                $result['req']=0;
                $result['msg']='The current email is already bound and cannot be changed';
                return $result;
            }
            MerchantModel::update(['email'=>$data['email'],'account'=>$data['email']],['id'=>self::$userID]);
        }

        $result['req']=1;
        return $result;
    }

    public function send($data){
        $code=mt_rand(1000,9999);
        $title='';
        //todo
        $code=1234;
        $info=[];
        switch ($data['type']){
            case config('data.code_type.login'):
                $content='The current verification code is '.$code.'【Valid within five minutes】';
                $title='Login';
                break;
            case config('data.code_type.phone'):
                $content='The current verification code is '.$code.'【Valid within five minutes】';
                $title='Change email';
                break;
            case config('data.code_type.logoff'):
                $content='The current verification code is '.$code.'【Valid within five minutes】';
                $title='Logoff';
                break;
            case config('data.code_type.email'):
                $content='The current verification code is '.$code.'【Valid within five minutes】';
                $title='Change binding email';
                break;
            case config('data.code_type.forget'):
                if($data['role']==config('data.role_type.merchant')){
                    $info=MerchantModel::where(['email'=>$data['email']])->where('status','>=',0)->field('salt,id')->find();
                }else{
                    $info=UserModel::where(['email'=>$data['email']])->where('status','>=',0)->field('salt,id')->find();
                }
                if(empty($info)) return false;
                $init_password=getRandomStr(6);
                $content='The new initial password is '.$init_password;
                $title='Modify password';
                break;
        }
        //todo
        if($data['type']==1){
            $flag=true;
        }else{
            $flag=send_email('lhb123',$title,$content,$data['email']);
        }
        if(!$flag) return false;

        if($data['type']!=config('data.code_type.forget')){
            //添加code记录
            CodeModel::where(['email'=>$data['email']])->update(['is_use'=>1]);
            $codeModel=new CodeModel();
            $result['code']=$code;
            $result['email']=$data['email'];
            $result['role']=$data['role'];
            $result['type']=$data['type'];
            $result['create_time']=time();
            $result['expire_time']=time()+config('data.code_expire');
            $flag=$codeModel->save($result);
        }

        if($data['type']==config('data.code_type.forget')){
            $password=sha1($info['salt'].$init_password);
            if($data['role']==config('data.role_type.merchant')){
                $flag=MerchantModel::update(['password'=>$password],['id'=>$info['id']]);
            }else{
                $flag=UserModel::update(['password'=>$password],['id'=>$info['id']]);
            }

        }
        return $flag;
    }

    public  function password($data){
        $type=self::$userType;
        if($type==config('data.role_type.user')){
            $salt=UserModel::where(['id'=>self::$userID])->value('salt');
            $password=sha1($salt.$data['password']);
            UserModel::update(['password'=>$password],['id'=>self::$userID]);
        }else{
            $salt=MerchantModel::where(['id'=>self::$userID])->value('salt');
            $password=sha1($salt.$data['password']);
            MerchantModel::update(['password'=>$password],['id'=>self::$userID]);
        }

        return true;
    }

    public function countries($word){
        $list=AreaModel::where(['type'=>'country'])->when($word,function ($query) use($word){
            $query->whereLike('name','%'.$word.'%');
        })->field('id,name,abbreviation,flag,phone_code')->order('name','asc')->select()->toArray();
        $hot=AreaModel::where(['type'=>'country','hot'=>1])->field('id,name,abbreviation,flag,phone_code')->order('name','asc')->select()->toArray();
        foreach ($list as $key=>$val){
            if($val['flag']){
                $list[$key]['flag']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($val['flag']);
            }else{
                $list[$key]['flag']='';
            }
        }
        foreach ($hot as $key=>$val){
            if($val['flag']){
                $hot[$key]['flag']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($val['flag']);
            }else{
                $hot[$key]['flag']='';
            }
        }
        $data['list']=doing($list);
        $data['hot']=$hot;
        return $data;
    }

    public function airports($data){
        $country_id=$data['country_id'];
        $word=$data['word'];
        $list=AirportModel::when($country_id,function ($query) use($country_id){
            $query->where(['country'=>$country_id]);
        })->when($word,function ($query) use($word){
            $query->whereLike('name','%'.$word.'%');
        })->field('id,name,iata,terminal terminal_list,country,city')->order('name','asc')->select()->toArray();

        foreach ($list as $key=>$val){
            $terminals=json_decode($val['terminal_list'],true);
            sort($terminals);
            $list[$key]['terminal_list']=$terminals;
            $areaInfo=AreaModel::where('id',$val['country'])->field('id,name,abbreviation,flag,phone_code')->find();

            $list[$key]['country_name']=$areaInfo['name'];
            $list[$key]['abbreviation']=$areaInfo['abbreviation'];
            $list[$key]['phone_code']=$areaInfo['phone_code'];
            if($areaInfo['flag']){
                $list[$key]['flag']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($areaInfo['flag']);
            }else{
                $list[$key]['flag']='';
            }
            $list[$key]['city_name']=AreaModel::where('id',$val['city'])->value('name');
        }
        return doing($list);
    }

    public function categories(){
        $list=CategoryModel::where(['pid'=>0])->field('id,name,icon,select_icon')->order('sort','desc')->select()->toArray();
        foreach ($list as $key=>&$value){
            if($value['icon']){
                $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['icon']);
            }else{
                $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.category_icon_default');
            }
            if($value['select_icon']){
                $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['select_icon']);
            }else{
                $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.category_select_icon_default');
            }
            $sub_category=CategoryModel::where(['pid'=>$value['id']])->field('id,name')->select()->toArray();
            if($sub_category){
                $value['sub_category']=$sub_category;
            }else{
                unset($list[$key]);
            }
        }
        return $list;
    }

    public function materials($type){
        if($type==1){
            $result=Db::table(config('database.prefix').'payment')->where(['is_delete'=>0,'status'=>1])->field('id,icon')->select();
            foreach ($result as &$value){
                $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['icon']);
            }
        }else{
            $result=Db::table(config('database.prefix').'feature')->where(['is_delete'=>0,'status'=>1])->field('id,name,icon,select_icon')->select();
            foreach ($result as &$value){
                if($value['icon']){
                    $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['icon']);
                }else{
                    $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.feature_icon_default');
                }
                if($value['select_icon']){
                    $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['select_icon']);
                }else{
                    $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.feature_select_icon_default');
                }
            }
        }
        return $result;
    }

    public function phoneCode(){
        $result=Db::table(config('database.prefix').'area')->where(['type'=>'country'])->field('id,name,flag,phone_code')->order('name','asc')->select();
        $hot_result=Db::table(config('database.prefix').'area')->where(['type'=>'country','hot'=>1])->field('id,name,flag,phone_code')->order('name','asc')->select();
        foreach ($result as &$value) {
            if ($value['flag']) {
                $value['flag'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . get_file_path($value['flag']);
            } else {
                $value['flag'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/' . config('data.country_icon_default');
            }
            $value['initials']=getFirstCharter($value['name']);
        }
        foreach ($hot_result as &$val) {
            if ($val['flag']) {
                $val['flag'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . get_file_path($val['flag']);
            } else {
                $val['flag'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/' . config('data.country_icon_default');
            }
        }

        $data['list']=$result;
        $data['hot']=$hot_result;
        return $data;
    }

    public function upload($data){
        $arr=[];
        $files=request()->file();
        //上传
        $file=$files['file'];
        $path= 'uploads/'.$data['scene'].'/';
        $info = $file->move($path);
        if($info){
            $arr['path']=$path.$info->getSaveName();
            $arr['url']=$_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/' .$arr['path'];
            $arr['poster']='';
            $arr['duration']='';
            if($data['source_type']=='video'){
                //解析第一帧
                $pathInfo=pathinfo($arr['path']);
                $poster=$pathInfo['dirname'].'/'.$pathInfo['filename'].'.jpg';
                getVideoCover($_SERVER['DOCUMENT_ROOT'].'/'.$arr['path'],1,$_SERVER['DOCUMENT_ROOT'].'/'.$poster);
                $duration=getTime($_SERVER['DOCUMENT_ROOT'].'/'.$arr['path']);
                $arr['poster']=$poster;
                $arr['duration']=$duration;
            }
            return $arr;
        }else{
            return false;
        }
    }

    public function labels(){
        return LabelModel::where(['status'=>1,'is_delete'=>0])->field('id,name,color')->select()->toArray();
    }

    public function uploads($data){
        $files=request()->file();
        $images_arr=[];
        $images=$files['file'];
        foreach($images as $image){
            $info = $image->move( './uploads/'.$data['scene']);
            if($info){
                $path='uploads/'.$data['scene'].'/'.$info->getSaveName();
                $images_arr[]=$path;
//                $url_arr[]=$_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/' .$path;
            }else{
                $images_arr[]='';
//                return false;
            }
        }
        return $images_arr;
    }

    public function addCode($data){
        $data['expire_time']=time()+config('data.code_expire');
        $data['create_time']=time();
        return CodeModel::insert($data);
    }

    public function getContent($key){
        return Db::table(config('database.prefix').'config_content')->where('key','=',$key)->value('content');
    }

    public function getUuid(){
        $uuid=getUUid();
        return $uuid;
    }

    public function handleCode($params){
        $qrcodeModel=new QrCodeModel();
        if($params['type']==1){
            //验证uuid
            if(empty($qrcodeModel->is_exists($params['uuid']))){
                return -1;
            }
            $token=getToken($params,3);
            QrCodeModel::where(['uuid'=>$params['uuid']])->update([
                'status'=>1,
                'update_time'=>date('Y-m-d H:i:s')
            ]);
            return $token;
        }elseif($params['type']==2){
            //验证token
            $data=verification($params['token'],3);
            $user_id=$data['data']->id;
            $user_info['id']=$user_id;
            $user_info['country']=0;

            $user_info['type']=config('data.role_type')['user'];

            $token=getToken($user_info,1);
            QrCodeModel::where(['uuid'=>$params['uuid']])->update([
                'status'=>2,
                'access_token'=>$token,
                'update_time'=>date('Y-m-d H:i:s')
            ]);
            return $token;
        }else{
            QrCodeModel::where(['uuid'=>$params['uuid']])->update([
                'status'=>3,
                'update_time'=>date('Y-m-d H:i:s')
            ]);
            return 3;
        }

    }

    public function getCode($params){
        $res=QrCodeModel::where(['uuid'=>$params['uuid']])->field('status,access_token')->find();
        if($res){
            $res=$res->toArray();
            $access_token=$res['access_token'];
            $status=$res['status'];
            if($status==2){
                $tokenInfo=verification($access_token,1);
                $result['id'] = $tokenInfo['data']->id;
                $result['type']=config('data.role_type')['user'];
                $result['country']=0;
                $result['access_token']=$access_token;
                $result['refresh_token']=getToken($result,2);
                //拼接userInfo信息
                $info=UserModel::where('id',$result['id'])->field('username,country,avatar')->find()->toArray();
                $result['scene']=1; //登录场景
                $result['username']=$info['username'];
                //获取用户头像
                if(!isset($info['avatar']) || empty($info['avatar'])){
                    $result['avatar']=get_file_path(config('data.user_avatar_default')[0]);
                }else{
                    $result['avatar']=get_file_path($info['avatar']);
                }
                Session::clear();
                Session::set('userId',$result['id']);
//            Session::set('userName',$info['username']);
                Session::set('userType',$result['type']);
                return $result;
            }
            return $res;
        }else{
            return $res;
        }
    }
}

